<?php

namespace comments\model;

require_once("comments/model/Comment.php");

class CommentDAL {

	private static $commentTable = "comments";

	private $mysqli;

 	public function __construct(\common\model\BaseDAL $baseDAL) {
 		$this->mysqli = $baseDAL->mysqli;
 	}

 	/**	
     * Returns an array of comments from the database
     * @return array comments
     */
    public function getAllComments($postId) {
        $comments = array();
        $sql = "SELECT pk, comment, commenterId, ownerId, Date 
        		FROM ".self::$commentTable." 
        		WHERE ownerid='".$postId."';";

        $statement = $this->mysqli->prepare($sql);
        if ($statement === false) {
            throw new \Exception("Preparation of $sql statement failed");
        }
        if ($statement->execute() === false) {
            throw new \Exception("Execution of $sql statement failed");
        }
        $result = $statement->get_result();
        while ($object = $result->fetch_array(MYSQLI_ASSOC))
        {
            $comments[] = new \comments\model\Comment($object["comment"], 
    												  $object["commenterId"],
    												  $object["Date"],
                                                      $object["pk"]);
        }
        return $comments;
    }

    /**
    * @param User user 
    * @throws Exception if something goes wrong.
    */
    public function addComment(\comments\model\Comment $comment) {
    	$text = $comment->comment;
    	$userId = $comment->commentOwner;
    	$postId = $comment->postId; 

    	if ($text == "" || $userId == "" || $postId == "") {
    		throw new \Exception("Commen entry is empty");
    	}
                
		$sql = "INSERT INTO ".self::$commentTable."( comment, commenterId, ownerId ) VALUES(?, ?, ?)";        
		$statement = $this->mysqli->prepare($sql);      
        if ($statement === false) {
            throw new \Exception("Preparation of $sql statement failed");
        }
        if ($statement->bind_param("sii" ,$text, $userId, $postId) === false) {
            throw new \Exception("Binding of $sql failed");
        }
        if ($statement->execute() === false) {
            throw new \Exception("Execution of $sql failed");
        }
    	
    }

    /**
    * @param User user 
    * @param int $commentId 
    * @throws Exception if something goes wrong.
    */
    public function updateComment(\comments\model\Comment $comment) {
        $text = $comment->comment;        
        if ($text == "") {
            throw new \Exception("Input was empty");
        }              
        $sql = "UPDATE ".self::$commentTable." SET comment = ? WHERE pk = $comment->commentId";    
        $statement = $this->mysqli->prepare($sql);      
        if ($statement === false) {
            throw new \Exception("Preparation of $sql statement failed");
        }
        if ($statement->bind_param("s" ,$text) === false) {
            throw new \Exception("Binding of $sql failed");
        }
        if ($statement->execute() === false) {
            throw new \Exception("Execution of $sql failed");
        }    
    }

    /**
    * @param User user 
    * @param int $commentId 
    * @throws Exception if something goes wrong.
    */
    public function deleteComment(\comments\model\Comment $comment) {
        $sql = "DELETE FROM ".self::$commentTable." WHERE pk = $comment->commentId";    
        $statement = $this->mysqli->prepare($sql);      
        if ($statement === false) {
            throw new \Exception("Preparation of $sql statement failed");
        }
        if ($statement->execute() === false) {
            throw new \Exception("Execution of $sql failed");
        }    
    }
    
	
	/**
    * From https://coursepress.lnu.se/kurs/webbutveckling-med-php/exempelsida/mysqli-och-dal/
    * Only run on new system
    */
    public function createCommentTable() {
        $sqlStmt = "CREATE TABLE `".self::$commentTable."` 
            (
                `pk` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
                `comment` VARCHAR(255),
                `commenterId` INT NOT NULL,
                `ownerId` INT NOT NULL,
                `Date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (ownerId) REFERENCES posts (pk) ON DELETE CASCADE ON UPDATE CASCADE,
                FOREIGN KEY (commenterId) REFERENCES users (pk) ON DELETE CASCADE ON UPDATE CASCADE
            )
            ENGINE = innoDB;";
       
      if ($this->mysqli->query($sqlStmt) === false) {
          throw new \Exception("'$sqlStmt' failed ");
      }
    }
}